import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import request from '@/utils/request'

export const useUserStore = defineStore('user', () => {
  // 用户信息状态
  const userInfo = ref({
    id: '',
    userName: '',
    userAvatar: null,
    userProfile: null,
    userRole: 'user',
    createTime: '',
    updateTime: ''
  })
  
  // 登录状态
  const isLoggedIn = ref(false)
  const loading = ref(false)

  // 计算属性
  const displayName = computed(() => userInfo.value.userName || '未设置用户名')
  const roleText = computed(() => {
    const roleMap = {
      'user': '普通用户',
      'admin': '管理员',
      'super_admin': '超级管理员'
    }
    return roleMap[userInfo.value.userRole] || '未知角色'
  })

  // 获取用户信息
  const fetchUserInfo = async () => {
    loading.value = true
    try {
      const response = await request.get('/user/get/login')
      if (response && response.code === 0) {
        userInfo.value = response.data
        isLoggedIn.value = true
        return response.data
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 设置用户信息
  const setUserInfo = (data) => {
    userInfo.value = { ...userInfo.value, ...data }
    isLoggedIn.value = true
  }

  // 更新用户信息
  const updateUserInfo = async (data) => {
    loading.value = true
    try {
      // 这里可以调用更新用户信息的API
      // const response = await request.put('/user/update', data)
      
      // 暂时直接更新本地状态
      userInfo.value = { ...userInfo.value, ...data }
      return userInfo.value
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 清除用户信息（登出）
  const clearUserInfo = () => {
    userInfo.value = {
      id: '',
      userName: '',
      userAvatar: null,
      userProfile: null,
      userRole: 'user',
      createTime: '',
      updateTime: ''
    }
    isLoggedIn.value = false
    // 清除localStorage
    localStorage.removeItem('user_info')
    localStorage.removeItem('admin_token')
  }

  // 从localStorage恢复用户信息
  const restoreUserInfo = () => {
    const savedUserInfo = localStorage.getItem('user_info')
    const token = localStorage.getItem('admin_token')
    
    if (savedUserInfo && token) {
      try {
        const parsedUserInfo = JSON.parse(savedUserInfo)
        userInfo.value = parsedUserInfo
        isLoggedIn.value = true
      } catch (error) {
        console.error('恢复用户信息失败:', error)
        clearUserInfo()
      }
    }
  }

  return {
    // 状态
    userInfo,
    isLoggedIn,
    loading,
    
    // 计算属性
    displayName,
    roleText,
    
    // 方法
    fetchUserInfo,
    setUserInfo,
    updateUserInfo,
    clearUserInfo,
    restoreUserInfo
  }
})